const Koa = require('koa');
const Router = require('koa-router');
const { koaBody } = require('koa-body');
const static = require('koa-static');
const mount = require('koa-mount');

let _ = require('lodash');

const http = require('http');
const WebSocket = require('ws');

let apilist = require('./api/apilist')
let serverroute = require('./serverroute')

let execTask = require('./execTask')

let killport = require('./killport')

const config = require('./config'); // 引入配置文件


const { exec, spawn } = require('child_process');
const { promisify } = require('util');
const execPromise = promisify(exec); // 将 exec 转换为 Promise 形式


killport.killPort(8889).then(res => {
  
  execPromise('cd C:\\Users\\Administrator\\Desktop\\geoserver-2.25.6-bin && java -jar -DGEOSERVER_DATA_DIR="data_dir" -Djava.awt.headless=true -Dfile.encoding=UTF-8 -DSTOP.PORT=8079 -DSTOP.KEY=geoserver -jar start.jar',{
    maxBuffer: 1024 * 1024 * 1024 // 设置为 10MB
  }).then(res => {
  
  })
})


const app = new Koa();
const server = http.createServer(app.callback());

let globalpre = '/api'

const router = new Router({
  prefix: config.globalpre
});

// 添加ws

// 创建 WebSocket 服务器，绑定到 HTTP 服务器并设置路径前缀
const wss = new WebSocket.Server({
  server,
  path: globalpre + '/wssjgl' // 指定 WebSocket 路径
});

let wslist = {

}

global.wslist = wslist

// 处理 WebSocket 连接
wss.on('connection', (ws, req) => {
  console.log('客户端已连接');

  let wsid = req.connection.remoteAddress || req.socket.remoteAddress;

  wsid = wsid + '|' + _.random(0, 999999)
  wslist[wsid] = ws

  // 接收消息
  ws.on('message', (message) => {
    console.log('收到消息:', message.toString());
    ws.send(`服务器回复：${message}`); // 发送回复
  });

  // 处理关闭事件
  ws.on('close', () => {
    console.log('客户端断开连接' + wsid);
    delete wslist[wsid]
  });

});


// 添加路由api
serverroute.serverroute(router)

// 静态文件目录添加前缀 /static
app.use(mount('/api/suoluetu',static(config.task.suoluetudir)));

// 注册中间件
app.use(
  koaBody({
    multipart: true, // 支持文件上传
    urlencoded: true, // 解析表单数据
  })
);
app.use(router.routes());
app.use(router.allowedMethods());

execTask.start()

// 启动服务器
server.listen(config.server.port, () => {
  console.log('服务器运行在 http://localhost:3000');
  console.log('WebSocket 路径：ws://localhost:3000/ws');
});
// app.listen(3000, () => {
//   console.log('Server running on http://localhost:3000/api/dirimglist?dirpath=D:\\xiangmu\\shujuguanli\\test');
// });